package com.openget.util;
import java.io.*;

import org.xml.sax.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class XmlUtil {
	
	private static final DocumentBuilder documentBuilder = createDocumentBuilder();
	private static final XPath xPath = createXPath();
	
	public static DocumentBuilder createDocumentBuilder(){
		try
		{
			return DocumentBuilderFactory.newInstance().newDocumentBuilder();
		}
		catch (Exception e) { }
		
		return null;		
	}
	
	public static XPath createXPath(){
		return XPathFactory.newInstance().newXPath();
	}

	public static Document createDocument(InputStream is) {
		try {
			return documentBuilder.parse(is);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static Element SelectSingleNode(String expression, Object node) {
		try {
			return (Element)xPath.evaluate(expression, node, XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static NodeList SelectNodes(String expression, Object node) {
		try {
			return (NodeList)xPath.evaluate(expression, node, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
